package com.ruoyi.ftrl.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.ftrl.domain.Dto.*;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.checkerframework.checker.units.qual.A;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.ftrl.domain.EquipmentDocking;
import com.ruoyi.ftrl.service.IEquipmentDockingService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 室温实时数据Controller
 *
 * @author dihang
 * @date 2024-07-09
 */
@RestController
@RequestMapping("/ftrl/docking")
public class EquipmentDockingController extends BaseController
{
    @Autowired
    private IEquipmentDockingService equipmentDockingService;

    /**
     * 各个设备数量以及在线率（大屏 设备管理）
     */
    @GetMapping("/equipment")
    public TableDataInfo selectEquipmentDockings()
    {
        List<Equipment> equipment = equipmentDockingService.selectEquipmentDockings();
        return getDataTable(equipment);

    }

    /**
     * 供暖概况室内外曲线（大屏）
     */
    @GetMapping("/history/list/stance/{id}")
    public AjaxResult stanceHistory(@PathVariable("id") Long id)
    {
        return success(equipmentDockingService.selectEquipmentDockingStanceById(id));

    }


    /**
     * 驾驶舱小区历史曲线（大屏展示）
     */
    @GetMapping("/history/list/stance")
    public AjaxResult stanceHistory(TempsDtos tempsDto)
    {
        return success(equipmentDockingService.selectEquipmentDockingStance(tempsDto));

    }



    /**
     * 室温分析界面温度最高值，最低值，平均值
     */

    @GetMapping(value = "count")
    public AjaxResult getCount()
    {
        return success(equipmentDockingService.selectEquipmentDockingCount());
    }



    /**
     * 数据分析（大屏展示）
     */
    @GetMapping("/history/list/date")
//    public TableDataInfo dataAnalysis(DateDto dateDto)
//    {
//        startPage();
//        List<EquipmentDocking>list=equipmentDockingService.selectEquipmentDockingByIds(dateDto);
//        return getDataTable(list);
//    }
public TableDataInfo dataAnalysis(DateDto dateDto) throws ParseException {
//    startPage();  // 若依分页支持
    List<DailyTemperatureDto> list = equipmentDockingService.selectEquipmentDockingByIds(dateDto);
    return getDataTable(list);
}

    /**
     * 室温分析 数据导出
     * @param response
     * @param dateDto
     * @throws ParseException
     */
    @PostMapping("/history/list/export")
    public void exportDataAnalysis(HttpServletResponse response, DateDto dateDto) throws ParseException {
        // 禁用分页，获取全部数据
        List<DailyTemperatureDto> list = equipmentDockingService.selectEquipmentDockingByIds(dateDto);

        // 使用若依的 Excel 工具类导出
        ExcelUtil<DailyTemperatureDto> util = new ExcelUtil<>(DailyTemperatureDto.class);
        util.exportExcel(response, list, "室温分析数据");
    }


    /**
     * 历史曲线（大屏展示）
     */
    @GetMapping("/history/list/curve")
    public AjaxResult curveHistory(DateDto dateDto)
    {

        return success(equipmentDockingService.selectEquipmentDockingCurveHour(dateDto));
    }

    /**
     * 根据历史曲线导出为excle表格
     * @param response
     * @param dateDto
     */
    @PostMapping("/history/export")
    public void export(HttpServletResponse response, DateDto dateDto) throws UnsupportedEncodingException {
        TempDto1 tempDto = equipmentDockingService.selectEquipmentDockingCurveHour(dateDto);

        List<ExportTemperatureData> dataList = new ArrayList<>();
        List<Date> times = tempDto.getTime();
        List<Category1> categories = tempDto.getCategoryList();

        if (categories.isEmpty()) {
            return;
        }

        // 获取室外温度类别
        Category1 outdoorTempCategory = categories.get(categories.size() - 1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 创建室外温度映射，处理数据不完整的情况
        Map<Integer, Double> outdoorTempMap = new HashMap<>();
        for (int i = 0; i < outdoorTempCategory.getData().size(); i++) {
            outdoorTempMap.put(i, Double.valueOf(outdoorTempCategory.getData().get(i)));
        }

        // 处理所有房间温度数据
        for (int i = 0; i < times.size(); i++) {
            // 获取室外温度，如果没有数据则使用上一个有效值或默认值
            Double outdoorTemp = outdoorTempMap.getOrDefault(i,
                    i > 0 ? outdoorTempMap.getOrDefault(i - 1, 0.0) : 0.0);

            // 处理每个房间的数据
            for (int j = 0; j < categories.size() - 1; j++) {
                Category1 category = categories.get(j);

                // 确保房间温度数据存在
                if (i < category.getData().size()) {
                    ExportTemperatureData data = new ExportTemperatureData();
                    data.setMeasurementTime(sdf.format(times.get(i)));
                    data.setRoomNumber(category.getName());
                    data.setTemperature(category.getData().get(i));
                    data.setOutdoorTemperature(Math.round(outdoorTemp));
                    dataList.add(data);
                }
            }
        }

        // 按房间号和时间排序
        dataList.sort(Comparator.comparing(ExportTemperatureData::getRoomNumber)
                .thenComparing(ExportTemperatureData::getMeasurementTime).reversed());
        // 设置导出文件名
        String fileName = "室内外历史曲线数据表.xlsx";
        // 获取当前时间并格式化
        LocalDateTime now = LocalDateTime.now();
        String timeStr = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        fileName = String.format("室内外历史曲线数据表_%s.xlsx", timeStr);


        // 处理文件名中文编码
        fileName = URLEncoder.encode(fileName, "UTF-8");

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

        // 导出数据
        ExcelUtil<ExportTemperatureData> util = new ExcelUtil<>(ExportTemperatureData.class);
        util.exportExcel(response, dataList, "历史室内外温度数据");
//        TempDto tempDto = equipmentDockingService.selectEquipmentDockingCurveHour(dateDto);
//
//        List<ExportTemperatureData> dataList = new ArrayList<>();
//        List<Date> times = tempDto.getTime();
//        List<Category> categories = tempDto.getCategoryList();
//
//        if (categories.isEmpty()) {
//            return;
//        }
//
//        // //假设最后一类是室外温度
//        Category outdoorTempCategory = categories.get(categories.size() - 1);
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        for (int i = 0; i < times.size(); i++) {
//            for (int j = 0; j < categories.size() - 1; j++) {
//                Category category = categories.get(j);
//
//                // Ensure the data list is not empty and has enough elements
//                if (i < category.getData().size() && i < outdoorTempCategory.getData().size()) {
//                    ExportTemperatureData data = new ExportTemperatureData();
//                    data.setMeasurementTime(sdf.format(times.get(i)));
//                    data.setRoomNumber(category.getName());
//                    data.setTemperature(category.getData().get(i));
//                    data.setOutdoorTemperature(outdoorTempCategory.getData().get(i));
//                    dataList.add(data);
//                }
//            }
//        }
//        dataList.sort(Comparator.comparing(ExportTemperatureData::getRoomNumber)
//                .thenComparing(ExportTemperatureData::getMeasurementTime).reversed());
//        ExcelUtil<ExportTemperatureData> util = new ExcelUtil<>(ExportTemperatureData.class);
//        util.exportExcel(response, dataList, "历史室温数据");
//        TempDto tempDto = equipmentDockingService.selectEquipmentDockingCurveHour(dateDto);
//
//        List<ExportTemperatureData> dataList = new ArrayList<>();
//        List<Date> times = tempDto.getTime();
//        List<Category> categories = tempDto.getCategoryList();
//
//        if (categories.isEmpty()) {
//            return;
//        }
//
//        // 获取室外温度类别
//        Category outdoorTempCategory = categories.get(categories.size() - 1);
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//
//        // 处理所有房间温度数据
//        for (int i = 0; i < times.size(); i++) {
//            // 确保有室外温度数据
//            if (i < outdoorTempCategory.getData().size()) {
//                Double outdoorTemp = Double.valueOf(outdoorTempCategory.getData().get(i));
//
//
//                // 处理每个房间的数据
//                for (int j = 0; j < categories.size() - 1; j++) {
//                    Category category = categories.get(j);
//
//                    // 确保房间温度数据存在
//                    if (i < category.getData().size()) {
//                        ExportTemperatureData data = new ExportTemperatureData();
//                        data.setMeasurementTime(sdf.format(times.get(i)));
//                        data.setRoomNumber(category.getName());
//                        data.setTemperature(category.getData().get(i));
//                        data.setOutdoorTemperature( Math.round(outdoorTemp));  // 设置室外温度
//                        dataList.add(data);
//                    }
//                }
//            }
//        }
//
//        // 按房间号和时间排序
//        dataList.sort(Comparator.comparing(ExportTemperatureData::getRoomNumber)
//                .thenComparing(ExportTemperatureData::getMeasurementTime).reversed());
//
//        // 导出数据
//        ExcelUtil<ExportTemperatureData> util = new ExcelUtil<>(ExportTemperatureData.class);
//        util.exportExcel(response, dataList, "历史室温数据");
    }

    /**
     * 室温分析户主信息（大屏展示）
     */
    @GetMapping("/history/list/person")
    public AjaxResult curveHistory(String roomNo)
    {

        return success(equipmentDockingService.selectEquipmentDockingPerson(roomNo));
    }


    /**
     * 历史数据（大屏展示）
     */
    @GetMapping("/history/list/history")
    public TableDataInfo dataHistory(@RequestParam Map<String, Object> params)
    {
        List<String> roomNos = new ArrayList<>();
        params.forEach((key, value) -> {
            if (key.startsWith("roomNos")) {
                roomNos.add(value.toString());
            }
        });

        DateDto dateDto = new DateDto();
        dateDto.setRoomNos(roomNos);
        dateDto.setBeginRecordDate((String) params.get("params[beginRecordDate]"));
        dateDto.setEndRecordDate((String) params.get("params[endRecordDate]"));
        startPage();
        List<EquipmentDocking>list=equipmentDockingService.selectEquipmentDockingByroomNos(dateDto);
        return getDataTable(list);
    }

    /**
     * 室温分析点击房间后户主历史信息数据
     */
    @GetMapping("/history/list/person/history")
//    public TableDataInfo curveHistorys(RoomNoDto dateDto)
    public TableDataInfo curveHistorys(String roomNo)
    {
        startPage();
        List<EquipmentDocking>list=equipmentDockingService.selectEquipmentDockingPersonHistorys(roomNo);
//        List<EquipmentDocking>list=equipmentDockingService.selectEquipmentDockingPersonHistory(dateDto);
        return getDataTable(list);
    }

    /**
     * 查询单个房间室温历史数据列表
     */

    @GetMapping("/history/list/roomNo")
    public TableDataInfo listHistoryRoom(String  roomNo,Date startTime,Date endTime)
    {
        startPage();
        List<EquipmentDocking> list = equipmentDockingService.selectEquipmentDockingListHistoryRoom(roomNo,startTime,endTime);
        return getDataTable(list);
    }


    /**
     * 查询室温历史数据列表
     */
    @PreAuthorize("@ss.hasPermi('ftrl:docking:list')")
    @GetMapping("/history/list")
    public TableDataInfo listHistory(EquipmentDocking equipmentDocking)
    {
        startPage();
        List<EquipmentDocking> list = equipmentDockingService.selectEquipmentDockingListHistory(equipmentDocking);
        return getDataTable(list);
    }

    /**
     * 查询并拉取黑蚂蚁实时室温数据
     */

    @GetMapping("/lists")
    public Object lists()
    {
       Object object= equipmentDockingService.selectEquipmentDockingLists();
        return object;
    }
    /**
     * 查询并拉取黑蚂蚁实时室温数据（除2023对接小区）
     */

    @GetMapping("/listss")
    public Object listss()
    {
        Object object= equipmentDockingService.selectEquipmentDockingListsss();
        return object;
    }

    /**
     * 查询室温实时数据列表
     */
    @PreAuthorize("@ss.hasPermi('ftrl:docking:list')")
    @GetMapping("/list")
    public TableDataInfo list(EquipmentDocking equipmentDocking)
    {
        startPage();
        List<EquipmentDocking> list = equipmentDockingService.selectEquipmentDockingList(equipmentDocking);
        return getDataTable(list);
    }

    /**
     * 导出室温实时数据列表
     */
//    @PreAuthorize("@ss.hasPermi('ftrl:docking:export')")
//    @Log(title = "室温实时数据", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, EquipmentDocking equipmentDocking) throws UnsupportedEncodingException {
//
//        List<EquipmentDocking> list = equipmentDockingService.selectEquipmentDockingListss(equipmentDocking);
//        // 设置导出文件名
//        String fileName = "室温实时数据表.xlsx";
//        // 获取当前时间并格式化
//        LocalDateTime now = LocalDateTime.now();
//        String timeStr = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
//        fileName = String.format("室温实时数据表_%s.xlsx", timeStr);
//
//
//        // 处理文件名中文编码
//        fileName = URLEncoder.encode(fileName, "UTF-8");
//
//        // 设置响应头
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setCharacterEncoding("utf-8");
//        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
//        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
//        ExcelUtil<EquipmentDocking> util = new ExcelUtil<EquipmentDocking>(EquipmentDocking.class);
//        util.exportExcel(response, list, "室温实时数据数据");
//    }

    /**
     * 导出选中的室温实时数据列表
     */

    @PreAuthorize("@ss.hasPermi('ftrl:docking:export')")
    @Log(title = "室温实时数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export1(HttpServletResponse response, @RequestParam("roomNos") List<String> roomNos) throws UnsupportedEncodingException {
        // 参数校验
        if (roomNos == null || roomNos.isEmpty()) {
            throw new RuntimeException("请选择要导出的房间");
        }

        // 根据房间编号数组查询数据
        List<EquipmentDocking> list = equipmentDockingService.selectEquipmentDockingByRoomNos(roomNos.toArray(new String[0]));

        // 设置导出文件名
        LocalDateTime now = LocalDateTime.now();
        String timeStr = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String fileName = String.format("室温实时数据表_%s.xlsx", timeStr);

        // 处理文件名中文编码
        fileName = URLEncoder.encode(fileName, "UTF-8");

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

        ExcelUtil<EquipmentDocking> util = new ExcelUtil<EquipmentDocking>(EquipmentDocking.class);
        util.exportExcel(response, list, "室温实时数据");
    }

    /**
     * 获取室温实时数据详细信息
     */
    @PreAuthorize("@ss.hasPermi('ftrl:docking:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(equipmentDockingService.selectEquipmentDockingById(id));
    }

    /**
     * 新增室温实时数据
     */
    @PreAuthorize("@ss.hasPermi('ftrl:docking:add')")
    @Log(title = "室温实时数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EquipmentDocking equipmentDocking)
    {
        return toAjax(equipmentDockingService.insertEquipmentDocking(equipmentDocking));
    }

    /**
     * 修改室温实时数据
     */
    @PreAuthorize("@ss.hasPermi('ftrl:docking:edit')")
    @Log(title = "室温实时数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EquipmentDocking equipmentDocking)
    {
        return toAjax(equipmentDockingService.updateEquipmentDocking(equipmentDocking));
    }

    /**
     * 删除室温实时数据
     */
    @PreAuthorize("@ss.hasPermi('ftrl:docking:remove')")
    @Log(title = "室温实时数据", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(equipmentDockingService.deleteEquipmentDockingByIds(ids));
    }

    /**
     * 获取温度数据(饼状图）
     * @return
     */
    @GetMapping("/temperatureData")
    public Map<String, Object> getTemperatureData() {
        // 调用服务层方法获取数据
        return equipmentDockingService.getTemperatureData();
    }

    /**
     * 导出每个小区的平均温度
     */
    @PostMapping("/exportAvgTemp")
    public void exportAvgTemp(
            HttpServletResponse response,
            @RequestBody TempExportRequestDto requestDto
    ) {
        LocalDate startDate;
        LocalDate endDate;

        // 检查日期是否为空
        if (requestDto.getStartTime() != null && requestDto.getEndTime() != null) {
            // 解析日期
            startDate = LocalDate.parse(requestDto.getStartTime());
            endDate = LocalDate.parse(requestDto.getEndTime());

            // 检查日期范围是否超过五天
            if (ChronoUnit.DAYS.between(startDate, endDate) >= 5) {
                throw new IllegalArgumentException("日期范围不能超过五天");
            }
        } else {
            // 如果日期为空，设置为前一天
            LocalDate yesterday = LocalDate.now().minusDays(1);
            startDate = yesterday;
            endDate = yesterday;
        }

        try {
            // 调用业务层获取导出的数据
            List<AvgTempDto> avgTempList = equipmentDockingService.getAvgTempByTimeRange(requestDto);

            // 设置导出文件名
            LocalDateTime now = LocalDateTime.now();
            String timeStr = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            String fileName = String.format("小区平均室内温度统计表_%s.xlsx", timeStr);

            // 处理文件名中文编码
            fileName = URLEncoder.encode(fileName, "UTF-8");

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

            // 调用工具类生成 Excel 文件
            exportExcel(response, avgTempList,startDate,endDate);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出失败：" + e.getMessage());
        }
    }


//private void exportExcel(HttpServletResponse response, List<AvgTempDto> avgTempList) throws IOException {
//    Workbook workbook = new XSSFWorkbook();
//    Sheet sheet = workbook.createSheet("小区平均温度");
//
//    // 创建表头
//    Row headerRow = sheet.createRow(0);
//    headerRow.createCell(0).setCellValue("小区名称");
//    headerRow.createCell(1).setCellValue("日期");
//    headerRow.createCell(2).setCellValue("平均室内温度");
//
//    // 填充数据
//    Map<String, List<AvgTempDto>> groupedData = new HashMap<>();
//
//    for (AvgTempDto avgTemp : avgTempList) {
//        groupedData.computeIfAbsent(avgTemp.getVillageName(), k -> new ArrayList<>()).add(avgTemp);
//    }
//
//    int rowIndex = 1;
//    for (Map.Entry<String, List<AvgTempDto>> entry : groupedData.entrySet()) {
//        String villageName = entry.getKey();
//        List<AvgTempDto> temps = entry.getValue();
//
//        // 写入小区名称
//        int startRow = rowIndex; // 记录开始行
//        for (AvgTempDto temp : temps) {
//            Row row = sheet.createRow(rowIndex++);
//            if (temps.indexOf(temp) == 0) {
//                row.createCell(0).setCellValue(villageName); // 只在第一行写入小区名称
//            } else {
//                row.createCell(0).setCellValue(""); // 其他行留空
//            }
//            row.createCell(1).setCellValue(temp.getDate());
//            row.createCell(2).setCellValue(temp.getAvgTemp());
//        }
//
//        // 合并单元格
//        sheet.addMergedRegion(new CellRangeAddress(startRow, rowIndex - 1, 0, 0)); // 合并小区名称单元格
//    }
//
//    // 设置列宽
//    sheet.setColumnWidth(0, 20 * 256);
//    sheet.setColumnWidth(1, 20 * 256);
//    sheet.setColumnWidth(2, 20 * 256);
//
//    // 写入到输出流
//    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//    response.setHeader("Content-Disposition", "attachment; filename=小区平均温度统计表.xlsx");
//    workbook.write(response.getOutputStream());
//    workbook.close();
//}
    private void exportExcel(HttpServletResponse response, List<AvgTempDto> avgTempList, LocalDate startDate, LocalDate endDate) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("小区平均温度");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("小区名称");

        // 动态生成日期列
        int dateColumnIndex = 1;
        LocalDate currentDate = startDate;
        while (!currentDate.isAfter(endDate)) {
            headerRow.createCell(dateColumnIndex++).setCellValue(currentDate.toString());
            currentDate = currentDate.plusDays(1);
        }

        // 填充数据
        Map<String, Map<LocalDate, Double>> groupedData = new HashMap<>();

        for (AvgTempDto avgTemp : avgTempList) {
            String villageName = avgTemp.getVillageName();
            LocalDate date = LocalDate.parse(avgTemp.getDate());
            double avgTemperature = avgTemp.getAvgTemp();

            groupedData.computeIfAbsent(villageName, k -> new HashMap<>()).put(date, avgTemperature);
        }

        int rowIndex = 1;
        for (Map.Entry<String, Map<LocalDate, Double>> entry : groupedData.entrySet()) {
            String villageName = entry.getKey();
            Map<LocalDate, Double> temps = entry.getValue();

            Row row = sheet.createRow(rowIndex++);
            row.createCell(0).setCellValue(villageName); // 写入小区名称

            // 填充日期对应的平均温度
            for (int i = 1; i < dateColumnIndex; i++) {
                LocalDate date = startDate.plusDays(i - 1);
                Double temperature = temps.get(date);
                if (temperature != null) {
                    row.createCell(i).setCellValue(temperature);
                } else {
                    row.createCell(i).setCellValue(""); // 如果没有数据，留空
                }
            }
        }

        // 设置列宽
        sheet.setColumnWidth(0, 20 * 256);
        for (int i = 1; i < dateColumnIndex; i++) {
            sheet.setColumnWidth(i, 15 * 256); // 设置日期列宽
        }

        // 写入到输出流
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=小区平均温度统计表.xlsx");
        workbook.write(response.getOutputStream());
        workbook.close();
    }

//    private void exportExcel(HttpServletResponse response, List<AvgTempDto> avgTempList, LocalDate startDate, LocalDate endDate) throws IOException {
//        Workbook workbook = new XSSFWorkbook();
//        Sheet sheet = workbook.createSheet("小区平均温度");
//
//        // 创建表头
//        Row headerRow = sheet.createRow(0);
//        headerRow.createCell(0).setCellValue("小区名称");
//
//        // 动态生成日期列
//        int dateColumnIndex = 1;
//        LocalDate currentDate = startDate;
//        while (!currentDate.isAfter(endDate)) {
//            headerRow.createCell(dateColumnIndex++).setCellValue(currentDate.toString());
//            currentDate = currentDate.plusDays(1);
//        }
//
//        // 填充数据
//        Map<String, Map<LocalDate, Double>> groupedData = new HashMap<>();
//
//        for (AvgTempDto avgTemp : avgTempList) {
//            String villageName = avgTemp.getVillageName();
//            LocalDate date = LocalDate.parse(avgTemp.getDate());
//            double avgTemperature = avgTemp.getAvgTemp();
//
//            groupedData.computeIfAbsent(villageName, k -> new HashMap<>()).put(date, avgTemperature);
//        }
//
//        int rowIndex = 1;
//        for (Map.Entry<String, Map<LocalDate, Double>> entry : groupedData.entrySet()) {
//            String villageName = entry.getKey();
//            Map<LocalDate, Double> temps = entry.getValue();
//
//            Row row = sheet.createRow(rowIndex++);
//            row.createCell(0).setCellValue(villageName); // 写入小区名称
//
//            // 填充日期对应的平均温度
//            for (int i = 1; i < dateColumnIndex; i++) {
//                LocalDate date = startDate.plusDays(i - 1);
//                Double temperature = temps.get(date);
//                if (temperature != null) {
//                    row.createCell(i).setCellValue(temperature);
//                } else {
//                    row.createCell(i).setCellValue(""); // 如果没有数据，留空
//                }
//            }
//        }
//
//        // 设置列宽
//        sheet.setColumnWidth(0, 20 * 256);
//        for (int i = 1; i < dateColumnIndex; i++) {
//            sheet.setColumnWidth(i, 15 * 256); // 设置日期列宽
//        }
//
//        // 写入到输出流
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setHeader("Content-Disposition", "attachment; filename=小区平均温度统计表.xlsx");
//        workbook.write(response.getOutputStream());
//        workbook.close();
//    }

//    @PostMapping("/exportAvgTemp")
//    public void exportAvgTemp(
//            HttpServletResponse response,
//            @RequestParam(required = false) String startTime,
//            @RequestParam(required = false) String endTime
//    ) {
//        try {
//            TempExportRequestDto requestDto = new TempExportRequestDto();
//            requestDto.setStartTime(startTime);
//            requestDto.setEndTime(endTime);
//
//            // 检查时间段是否超过五天
//            if (isTimeRangeExceedingFiveDays(startTime, endTime)) {
//                throw new RuntimeException("导出失败：选择的时间段不能超过五天。");
//            }
//
//            // 调用业务层获取导出的数据
//            List<AvgTempDto> avgTempList = equipmentDockingService.getAvgTempByTimeRange(requestDto);
//
//            // 设置导出文件名
//            LocalDateTime now = LocalDateTime.now();
//            String timeStr = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
//            String fileName = String.format("小区平均室内温度统计表_%s.xlsx", timeStr);
//
//            // 处理文件名中文编码
//            fileName = URLEncoder.encode(fileName, "UTF-8");
//
//            // 设置响应头
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//            response.setCharacterEncoding("utf-8");
//            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
//            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
//
//            // 调用工具类生成 Excel 文件
//            ExcelUtil<AvgTempDto> util = new ExcelUtil<>(AvgTempDto.class);
//            util.exportExcel(response, avgTempList, "小区平均温度");
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new RuntimeException("导出失败：" + e.getMessage());
//        }
//    }

    /**
     * 获取小区平均室温数据（可按时间筛选）
     * @return
     */
    @GetMapping("/exportAvgTemp/list")
    public TableDataInfo selectExportAvgTempList(TempExportRequestDto requestDto){
//        startPage();
        List<AvgTempDto> avgTempList = equipmentDockingService.getAvgTempByTimeRange(requestDto);
        return getDataTable(avgTempList);
    }

    /**
     * 获取最高室温数据
     * @return
     */
    @GetMapping("/max")
    public TableDataInfo selectMax(){
        List<EquipmentDocking>equipmentDockingList=equipmentDockingService.selectEquipmentDockingMax();
        return getDataTable(equipmentDockingList);
    }



    /**
     * 获取最高低室温数据
     * @return
     */
    @GetMapping("/min")
    public TableDataInfo selectMin(){
        List<EquipmentDocking>equipmentDockingList=equipmentDockingService.selectEquipmentDockingMin();
        return getDataTable(equipmentDockingList);
    }

}
